﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace YArchitech.Temp
{
	internal class HYDuctSystemTree : TreeView
	{
		public HYDuctSystem HYDuctSystem
		{
			get
			{
				return this.m_HYDuctSystem;
			}
		}

		public TreeNode FindTreeNode(HYMEPObject comp)
		{
			TreeNode result = null;
			this.m_dicObjToNode.TryGetValue(comp, out result);
			return result;
		}

		public HYDuctStraight GetComponent(TreeNode tn)
		{
			if (tn.Tag == null)
			{
				return null;
			}
			return tn.Tag as HYDuctStraight;
		}

		public bool SelectComponent(HYMEPObject comp)
		{
			base.CollapseAll();
			TreeNode treeNode = this.FindTreeNode(comp);
			treeNode.Expand();
			base.SelectedNode = treeNode;
			return true;
		}

		public bool Attach(HYDuctSystem system)
		{
			base.Nodes.Clear();
			if (system == null)
			{
				return false;
			}
			this.m_HYDuctSystem = system;
			if (this.m_dicObjToNode != null)
			{
				this.m_dicObjToNode.Clear();
			}
			else
			{
				this.m_dicObjToNode = new Dictionary<HYMEPObject, TreeNode>();
			}
			this.AddObject(null, this.m_HYDuctSystem.Root);
			if (base.Nodes.Count == 0)
			{
				return false;
			}
			base.ExpandAll();
			base.Update();
			return true;
		}

		private void AddObject(TreeNode ndParent, HYMEPObject mepObj)
		{
			if (mepObj == null)
			{
				return;
			}
			if (mepObj is HYDuctStraight)
			{
				HYDuctStraight hyductStraight = mepObj as HYDuctStraight;
				TreeNode treeNode = new TreeNode();
				this.Binding(treeNode, hyductStraight);
				if (ndParent == null)
				{
					base.Nodes.Add(treeNode);
				}
				else
				{
					ndParent.Nodes.Add(treeNode);
				}
				this.AddObject(treeNode, mepObj.Next);
				if (!hyductStraight.HasTaper)
				{
					return;
				}
				IEnumerator<HYDuctTaper> enumerator = hyductStraight.Tapers.GetEnumerator();
				{
					while (enumerator.MoveNext())
					{
						HYDuctTaper mepObj2 = enumerator.Current;
						this.AddObject(ndParent, mepObj2);
					}
					return;
				}
			}
			if (mepObj is HYDuctTee)
			{
				this.AddObject(ndParent, mepObj.Next);
				HYDuctTee hyductTee = mepObj as HYDuctTee;
				this.AddObject(ndParent, hyductTee.Side);
				if (mepObj is HYDuctCross)
				{
					HYDuctCross hyductCross = mepObj as HYDuctCross;
					this.AddObject(ndParent, hyductCross.Side2);
					return;
				}
			}
			else if (!(mepObj is HYDuctTerminal))
			{
				this.AddObject(ndParent, mepObj.Next);
			}
		}

		private void Binding(TreeNode nd, HYDuctStraight mepObject)
		{
			nd.Text = mepObject.ShowString;
			nd.Tag = mepObject;
			this.m_dicObjToNode.Add(mepObject, nd);
		}

		private Dictionary<HYMEPObject, TreeNode> m_dicObjToNode;

		private HYDuctSystem m_HYDuctSystem;
	}
}
